import sys
from fmeter import getGLogger
from peer_pb2 import Transaction
import pdb

logger = getGLogger("fmeter")


def hex2Transaction(hex_str):
    """从16进制字符串反序列化为交易，从而能够获取其ID，在测HTTP请求的时候记录每个交易的请求时刻和响应时刻
    Args:
        hex_str 十六进制的交易字符串
    Returns:
        Transaction: 交易
    """
    t = Transaction()
    try:
        t.ParseFromString(bytearray.fromhex(hex_str))
    except Exception as e:
        pdb.set_trace()
        logger.error(e)
    return t


def loadPayload(fpath):
    with open(fpath) as f:
        raw_payload_list = [line.strip() for line in f]
        payload_list = [(hex2Transaction(tx.strip("\"")).id, tx) for tx in raw_payload_list]
        return payload_list


def writeList2File(fpath, payload_list):
    with open(fpath, "w") as f:
        payload_list = map(lambda x: ",".join(x), payload_list)
        f.write("\n".join(payload_list))
        f.write("\n")


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("usage: {} RepChainApi-*.txt".format(sys.argv[0]))
        sys.exit()
    payload_list = loadPayload(sys.argv[1])
    writeList2File("../payload_list.txt", payload_list)
